//
//  Configuration.m
//  Mockup
//
//  Created by Bernardo Quibiana on 2/20/10.
//  Copyright 2010 Mac-Easy@USC. All rights reserved.
//

#import "Configuration.h"

//static Configuration * theConfiguration = nil;

@implementation Configuration



@synthesize settings; 
@synthesize highScores;

static Configuration * sharedConfiguration = nil;

+(Configuration *) sharedInstance {
	
	if (sharedConfiguration == nil) {
		NSLog(@"Configuration:\tInitializing the shared configuration");
		sharedConfiguration = [[super allocWithZone:NULL] init];
		
		if (sharedConfiguration == nil) {
			NSLog(@"Configuratioin:\tStill nil");
		}
		[sharedConfiguration loadSettings];
		[sharedConfiguration loadHighScores];
	}
	
	
	return sharedConfiguration;
}

+(void) killSharedInstance {
	@synchronized(self){
#ifdef DEBUG
		NSLog(@"Configuration: Killing shared instance");
#endif
		NSLog(@"Configuration: Killing shared instance");
		
		if ([Configuration sharedInstance]) {
			[sharedConfiguration.settings release];
			[sharedConfiguration.highScores release];
			
			sharedConfiguration = nil;
		}
	}
}

+(id) allocWithZone:(NSZone *)zone{
	return [[self sharedInstance] retain];
}

-(id) copyWithZone:(NSZone *) zone{
	return self;
}

-(id)retain{
	return self;
}

-(NSUInteger) retainCount{
	return NSUIntegerMax;	// denotes an object that cannot be released
}

-(void) release{
	// do nothing
}

-(id) autorelease{
	return self;
}

-(void) loadSettings{
#ifdef DEBUG
	NSLog(@"Loading settings");
#endif
	NSString * path = [[NSBundle mainBundle] bundlePath];
	NSString * file = [path stringByAppendingPathComponent:@"settings.plist"];
	
	NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithContentsOfFile:file];
	self.settings = dic;
	
	NSLog(@"Configuration:\tsettings:\n%@", [settings description]);
	
	[dic release];
}

-(void) loadHighScores{
#ifdef DEBUG
	NSLog(@"Loading high scores");
#endif
	
	//NSString * path = [NSString stringWithFormat:@"%@/Library/Preferences/highscores", NSHomeDirectory()];
	NSString * path = [[NSBundle mainBundle] bundlePath];
	NSString * file = [path stringByAppendingPathComponent:@"highscores.plist"];
	
	Matrix * matrix = [[Matrix alloc] initWithContentsOfFile:file rowSize:15 colSize:2];
	self.highScores = matrix;
	
	NSLog(@"Configuration:\thigh scores: %@", [self.highScores description]);
	
	[matrix release];
}

-(void) saveSettings{
	NSString * path = [[NSBundle mainBundle] bundlePath];
	NSString * file = [path stringByAppendingPathComponent:@"settings.plist"];
	
	if ([self.settings writeToFile:file atomically:YES]) {
		printf("Configuration:\tSuccessfully saved settings\n");
	} else {
		printf("Configuration:\tFailure to save settings\n");
	}
}

+(void) saveSettings {
	if (sharedConfiguration) {
		NSLog(@"Saving settings");
		[sharedConfiguration saveSettings];
	} else {
		NSLog(@"Error: nil sharedConfiguration");
	}
}

-(void) saveHighScores{
	NSString * path = [[NSBundle mainBundle] bundlePath];
	NSString * file = [path stringByAppendingPathComponent:@"highscores.plist"];
	
	if ([self.highScores writeToFile:file atomically:YES]) {
		printf("Configuration:\tSuccessfully saved high scores\n");
	} else {
		printf("Configuration:\tCould not save high scores\n");
	}
}

+(void) saveHighScores {
	if (sharedConfiguration) {
		NSLog(@"Saving high scores");
		[sharedConfiguration saveHighScores];
	} else {
		NSLog(@"Error: nil sharedConfiguration");
	}
}

-(BOOL) savedGame {
	NSString * saved = [self.settings objectForKey:@"savedGame"];
	
	return [saved boolValue];
}

+(BOOL) savedGame {
	return [sharedConfiguration savedGame];
}

+(NSString *) getSavedGameFile {
	return @"saving.plist";
}

-(void) didSaveGame:(BOOL) saved{
	
	[self.settings setObject:[NSString stringWithFormat:@"%@", (saved? @"YES" : @"NO")] forKey:@"savedGame"];
	
	if ([self savedGame] != saved) {
		NSLog(@"Inconsistency");
	}
}

+(void) didSaveGame:(BOOL) saved {
	[sharedConfiguration didSaveGame:saved];
}

-(id) getSettingsValueForKey:(NSString *)key  {
	return [self.settings objectForKey:key];
}

-(Matrix *) getHighScoresForDifficulty:(difficulty_t)difficulty{
	NSRange rowRange;
	NSRange colRange = NSMakeRange(0, 2);
	
	switch (difficulty) {
		case Easy:
			rowRange = NSMakeRange(0, 5);
			break;
		case Medium:
			rowRange = NSMakeRange(5, 5);
			break;
		case Hard:
			rowRange = NSMakeRange(10, 5);
			break;
		default:
			rowRange = NSMakeRange(0, 5);
	}
	
	return [Matrix matrixWithMatrix:self.highScores rowRange:rowRange 
							colRange:colRange wrapAround:NO];
}


//MOD
-(NSInteger) checkHighScoreForDifficulty:(difficulty_t)difficulty withScore:(NSInteger)score {
	NSInteger pos = 0;
	NSInteger min = [self getMinIndexForDifficulty:difficulty];
	NSInteger max = min + 4;
	NSInteger temp;
	
	printf("MAX position: %d \n", max);
	
	for (pos = min; pos <= max;) {
		printf("Player score position: %d \n", pos);
		temp = [[self.highScores objectAtRow:pos andCol:1] intValue]; 
		printf("Comparing against HS: %d \n", temp);
		if ( temp > score) {
			pos++;
		} else {
			break;
		}
	}
	
	printf("position: %d \n", pos);
	
	if(pos-1 == max){
		printf("Returning -1..\n");
		return -1;
	}else{
		return pos;
	}
	//return	(pos - min);
}

-(NSInteger) getMinIndexForDifficulty:(difficulty_t) difficulty {
	switch (difficulty) {
		case Easy:
			return 0;
		case Medium:
			return 5;
		case Hard:
			return 10;
		default:
			return 0;
	}
}


-(void) setPreferredDifficulty:(difficulty_t) difficulty {
	NSString * item = [NSString stringWithFormat:@"%d", difficulty];
	[self.settings setObject:item forKey:@"preferredDifficulty"];
}

-(difficulty_t) getPreferredDifficulty{
	NSString * item = [self.settings objectForKey:@"preferredDifficulty"];
	return [item intValue];
}

+(void) setPreferredDifficulty:(difficulty_t) difficulty {
	[sharedConfiguration setPreferredDifficulty:difficulty];
}

+(difficulty_t) getPreferredDifficulty{
	return [sharedConfiguration getPreferredDifficulty];
}

-(BOOL) updateHighScoresForDifficulty:(difficulty_t)difficulty withName:(NSString *) username andScore:(NSInteger)score{
	printf("Inside the updateHighScoresForDifficulty method...\n");
	BOOL updated = NO;
	NSInteger min = [self getMinIndexForDifficulty:difficulty];
	NSInteger max = min + 4;
	NSInteger pos = [self checkHighScoreForDifficulty:difficulty withScore:score];
	
	NSString * aName;
	NSInteger aScore;
	
	for(NSInteger i = max; i>pos; i--){
		aName = [self.highScores objectAtRow:i-1 andCol:0];
		aScore = [[self.highScores objectAtRow:i-1 andCol:1] intValue];
		[self.highScores replaceObjectAtRow:i andCol:0 withObject:aName];
		[self.highScores replaceObjectAtRow:i andCol:1 withObject:[NSString stringWithFormat:@"%d",aScore]];
	}
	
	[self.highScores replaceObjectAtRow:pos andCol:0 withObject:username];
	[self.highScores replaceObjectAtRow:pos andCol:1 withObject:[NSString stringWithFormat:@"%d",score]];
	
	/**
	for (NSInteger i = pos; i <= max; i++) {
			aName = [self.highScores objectAtRow:i andCol:0];
			aScore = (NSInteger)[self.highScores objectAtRow:i andCol:0];
			[self.highScores replaceObjectAtRow:i andCol:0 withObject:username];
			[self.highScores replaceObjectAtRow:i andCol:1 withObject:[NSString stringWithFormat:@"%d",score]];
	}
	 **/
	
	return updated;
}

-(NSArray *) scoresForDifficulty:(difficulty_t)difficulty {	
	return [highScores getCol:1];
}

@end
